#!/usr/bin/env python2
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>

from __future__ import (unicode_literals, division, absolute_import,
                        print_function)
import sys
import os
import errno
import subprocess

from vms import ensure_vm, shutdown_vm, Rsync, to_vm, from_vm, run_main, get_calibre_dir
VM = 'osx-calibre-build'
rsync = Rsync(VM)
base = os.path.dirname(os.path.abspath(__file__))

if sys.argv[1:] == ['shutdown']:
    shutdown_vm(VM)
    raise SystemExit(0)


def abspath(x):
    return os.path.abspath(os.path.join(base, x))


def mkdir(x):
    try:
        os.mkdir(abspath(x))
    except EnvironmentError as err:
        if err.errno == errno.EEXIST:
            return
        raise


mkdir('sources-cache')
mkdir('build')
output_dir = os.path.join(abspath('build'), 'osx')
mkdir(output_dir)

if 'calibre' in sys.argv:
    # Ensure the iconssets are built
    if not os.path.exists(os.path.join(get_calibre_dir(), 'icons', 'icns', 'calibre.iconset')):
        print('Building iconsets...')
        subprocess.check_call([sys.executable, os.path.join(get_calibre_dir(), 'icons', 'icns', 'make_iconsets.py')])

ensure_vm(VM)
to_vm(rsync, output_dir)
try:
    run_main(VM, 'python', '/scripts/main.py', *sys.argv[1:])
finally:
    print()
    from_vm(rsync, output_dir)
